// request.js
import { cookie } from '@/utils/cookie.js'
import i18n from '@/locale/index'
// 定义基础 URL
const baseURL = 'http://api_cloud.vilionsmart.com';

// 计数器，用于跟踪正在进行的请求数量
let requestCount = 0;

// 统一错误处理
const handleError = (err) => {
	const t = i18n.global.t;
	let errorMessage = t('comm.networkErr');
	if (err) {
		errorMessage = err.errMsg || err;
	}
	uni.showToast({
		title: errorMessage,
		icon: 'none'
	});
	// 请求结束，计数器减1
	if (requestCount > 0) {
		requestCount--;
	}

	// 检查是否所有请求都已完成
	if (requestCount == 0) {
		uni.stopPullDownRefresh();
		setTimeout(() => {
			uni.hideLoading();
		}, 300)
	}
	return Promise.reject(err);
};

// 处理响应状态码和 code
const handleResponse = (res) => {
	const {
		statusCode,
		data
	} = res;
	// console.log('res',res)
	if (statusCode == 200) {
		const {
			code
		} = data;
		if (code == 200) {
			return data;
		} else if (code == 401) { // 假设 401 表示未登录或登录过期
			handleError(data.data)
			// 跳转到登录页面
			cookie.remove('token')
			uni.reLaunch({
				url: '/pages/login/index'
			});
			return data;
		} else {
			handleError(data.data)
		}
	}
	// 请求结束，计数器减1
	if (requestCount > 0) {
		requestCount--;
	}
	// 检查是否所有请求都已完成
	if (requestCount === 0) {
		uni.stopPullDownRefresh();
		setTimeout(() => {
			uni.hideLoading();
		}, 300)
	}
};

// 检查网络状态
const getNetworkType = () => {
	let type = false
	uni.getNetworkType({
		success: function (res) {
			console.log('res', res)
			if (res.networkType === 'none') {
				// console.log('无网络连接');
				type = false
			} else {
				// console.log('当前网络类型：', res.networkType);
				type = true
			}
		},
		fail: function (err) {
			// console.error('获取网络类型失败：', err);
			type = false
		}
	});
	return type
}


// 封装请求方法
const request = async (options, loadingText) => {
	// 请求开始，计数器加1
	requestCount += 1;
	console.log('requestCount', requestCount)
	if (requestCount == 1) {
		uni.showLoading({
			title: 'Loading...',
			mask: true
		});
	}
	// 检查网络状态
	const networkStatus = await getNetworkType();
	if (!networkStatus) {
		const t = i18n.global.t;
		return handleError(t('comm.no.network'));
	}
	// 获取 token
	const token = cookie.get('token');
	// console.log('tokentokentokentoken',token)
	const Language = cookie.get('applicationLocale')
	const nodeVal = cookie.get('nodeVal')
	let header = {
		'Accept-Language': Language ? Language : '',

	}
	if (nodeVal) {
		header.lookupKey = nodeVal
	}
	if (!options?.ignoreToken) {
		header.token = token ? token : '';
	}
	return new Promise((resolve, reject) => {
		// 合并请求配置
		const config = {
			url: baseURL + options.url,
			sslVerify: false,
			method: options.method || 'GET',
			data: options.data || {},
			header: {
				'Content-Type': 'application/json',
				...header
			},
			success: (res) => {
				const result = handleResponse(res);
				if (result) {
					// 请求结束，计数器减1
					if (requestCount > 0) {
						requestCount--;
					}
					// 检查是否所有请求都已完成
					if (requestCount === 0) {
						uni.stopPullDownRefresh();
						setTimeout(() => {
							uni.hideLoading();
						}, 300)
					}
					resolve(result);
				} else {
					reject(res.data.data)
				}
			},
			fail: (err) => {
				console.log('aaaaa', err)
				if (err.errMsg && err.errMsg == 'request:fail abort') {
					console.log('请求出错')
					uni.hideLoading()
				} else {
					reject(handleError(err));
				}
			}
		};
		uni.request(config)
	});
};
export default request;